<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class home extends MX_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('medical_disease_model');
        $this->load->model('medical_parts_model');
        $this->load->model('medical_department_model');
        $this->load->model('medical_symptoms_model');
        $this->load->model('medical_object_model');
        $this->load->model('cms_tag_model');
        $this->load->model('cms_category_model');
    }

    protected function _eventLoadLayout() {
        $this->page['title'] = 'Giải pháp y tế cộng đồng';
        $this->module['title'] = 'Giải pháp y tế cộng đồng';
    }

    function index() {
        try {
            $CI           = & get_instance();
            $CI->st_registry->clearMemcache();
            $list_disease = null;
            $data         = array();
            $season       = $this->season;
            $list_disease = $CI->st_registry->getKey('list_disease_home');

            //danh mục bệnh là khoa luôn
            $result_dep = $this->medical_disease_model->db->query("SELECT * FROM medical_department WHERE is_hidden = 1");
            $list_dep   = array();
            foreach ($result_dep->result() as $row) {
                $row->href          = BASE_URL . renderToAlias($row->name) . '-dp'.$row->id . '.html';
                $list_dep[$row->id] = $row;
            }
            $data['menu_medical'] = $list_dep;

            //danh mục tin tức
            $result_cat = $this->medical_disease_model->db->query("SELECT * FROM cms_category WHERE is_active = 1");
            $list_cat   = array();
            foreach ($result_cat->result() as $row) {
                $row->href          = BASE_URL . renderToAlias($row->name) . '-ca'.$row->id . '.html';
                $list_cat[$row->id] = $row;
            }
            $data['menu_news'] = $list_cat;

            //lấy bệnh theo mùa
            if(empty($list_disease)){
                foreach($season as $k => $v){
                    $query       = 'SELECT * FROM medical_disease WHERE CONCAT(",",season_ids,",") LIKE "%' .  $v['id'] . '%" AND is_hidden = 1 ORDER BY id DESC LIMIT 4';
                    $disease_res = $this->medical_disease_model->db->query($query);
                    if($disease_res){
                        foreach ($disease_res->result() as $row) {
                            $row->href              = BASE_URL . 'benh/' . $row->alias . '-ds'.$row->id . '.html';
                            $row->name              = $this->subString($row->name, 0, 50, '...');
                            $row->short_description = $this->subString($row->short_description, 0, 120, '...');
                            $list_disease[$k][]     = $row;
                        }
                    }
                }
                $CI->st_registry->setKey('list_disease_home', $list_disease, CACHE_TIMEOUT);
            }

            $list_top = $CI->st_registry->getKey('list_top_home');//get top disease
            if(empty($list_top)){

                $query_top   = 'SELECT * FROM medical_disease WHERE is_top = 1 AND is_hidden = 1 ORDER BY id DESC LIMIT 3';
                $disease_top = $this->medical_disease_model->db->query($query_top);
                if($disease_top){
                    foreach ($disease_top->result() as $row) {
                        $row->href  = BASE_URL . 'benh/' . $row->alias . '-ds'.$row->id . '.html';
                        $row->image = ($row->image) ? render_src($row->image) : BASE_URL. "themes/standard/images/top_test.jpg";
                        $row->date  = date('d-m-Y', $row->created_date);
                        $list_top[$row->id]     = $row;
                    }
                }

                $CI->st_registry->setKey('list_top_home', $list_top, CACHE_TIMEOUT);
            }

            $symptom_top = $CI->st_registry->getKey('symptom_top_home');//lấy top triệu chứng do hệ thống  chọn
            if(empty($symptom_top)){
                $query_sym = 'SELECT * FROM medical_symptoms WHERE is_hidden = 1 ORDER BY system_score DESC LIMIT 3';
                $symp_top  = $this->medical_disease_model->db->query($query_sym);
                if($symp_top){
                    foreach ($symp_top->result() as $row) {
                        $row->image            = ($row->image) ? render_src($row->image) : BASE_URL. "themes/standard/images/top_test.jpg";
                        $row->href             = BASE_URL . 'trieu-chung/' . renderToAlias($row->name) . '-st'.$row->id . '.html';
                        $symptom_top[$row->id] = $row;
                    }
                }

                $CI->st_registry->setKey('symptom_top_home', $symptom_top, CACHE_TIMEOUT);
            }

            $data['symptom_top']  = $symptom_top;
            $data['list_top']     = $list_top;
            $data['list_disease'] = $list_disease;
            $data['season']       = $season;
            $this->setPageContent('home/home_page', $data);
            $this->renderLayout('layouts/layout_home');
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    function list_news() {
        try {
            $this->load->view('home/list');
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    function detail() {
        try {
            $this->load->view('home/detail');
        } catch (Exception $ex) {
            echo $ex->getMessage();
        }
    }

    function subString($str, $start, $num, $ext=FALSE) {
        //$str = EnBacLib::plainText($str);

        if ($num > strlen($str) - $start)
            $num = strlen($str) - $start;

        if ($num <= 0)
            return '';

        $pos = strpos(substr($str, $start + $num + 1, strlen($str) - $start - $num - 1), ' ');

        $st = substr($str, $start, $num + $pos + 1);

        if ($ext && strlen($str) - $start > $num)
            $st.='..';

        return $st;
    }

    function cropImage($img_max, $width, $height){

        if($img_max){
            //$ext = end(explode(".",$img_max)); // bị lỗi version php
            $ext = strtolower($this->getExtension($img_max));
            $ext = str_replace('.', '', $ext);

            $full_image           = imagecreatefromjpeg($img_max);
            list($main_width, $main_height) = getimagesize($img_max);

            //crop img từ ảnh chính sang vùng chọn ảnh
            $selector = imagecreatetruecolor($width, $height);
            imagecopy($selector, $full_image, $width, $height, 0, 0, $main_width, $main_height);

            $file = 100;
            $this->parseImage($ext,$selector,$file);

            return $selector;
        }else{
            return '';
        }
    }

    function getExtension($file) {
        $pos = strrpos($file, '.');
        if (!$pos) {
            return false;
        }
        $str = substr($file, $pos, strlen($file));
        return strtolower($str);
    }

    function parseImage($ext,$img,$file = null){
        switch($ext){
            case "png":
                imagepng($img,($file != null ? $file : ''));
                break;
            case "jpeg":
                imagejpeg($img,($file ? $file : ''),99);
                break;
            case "jpg":
                imagejpeg($img,($file ? $file : ''),99);
                break;
            case "gif":
                imagegif($img,($file ? $file : ''));
                break;
        }
    }


}